<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px" size="small">
      <el-form-item label="作者" prop="author">
        <el-input v-model="queryParams.author" clearable placeholder="请输入作者" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="书籍名称" prop="title">
        <el-input v-model="queryParams.title" clearable placeholder="请输入书籍名称" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <div style="display: inline-block;">
          <treeselect v-model="queryParams.category" :normalizer="normalizer" :options="tagOptions" :show-count="true"
            placeholder="请选择分类" style="display: inline-block; width: 200px;" />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['business:book:add']" icon="el-icon-plus" plain size="mini" type="primary"
          @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['business:book:edit']" :disabled="single" icon="el-icon-edit" plain size="mini" type="success"
          @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['business:book:remove']" :disabled="multiple" icon="el-icon-delete" plain size="mini" type="danger"
          @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['business:book:export']" icon="el-icon-download" plain size="mini" type="warning"
          @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bookList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column label="序号" type="index" />
      <el-table-column align="center" label="封面" prop="img">
        <template slot-scope="scope">
          <el-image :src="getImgURL(scope.row.img)" fit="fill" style="width: 70px; height: 100px"></el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" label="作者" prop="author" />
      <el-table-column align="center" label="状态" prop="status" />
      <el-table-column align="center" label="类型" prop="type" />
      <el-table-column align="center" label="书籍名称" prop="title" />
      <el-table-column align="center" label="分类" prop="category" />
      <el-table-column align="center" label="描述" prop="desc" width="400" />
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button v-hasPermi="['business:book:edit']" icon="el-icon-edit" size="mini" type="text"
            @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-hasPermi="['business:book:remove']" icon="el-icon-delete" size="mini" type="text"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total"
      @pagination="getList" />

    <!-- 添加或修改图书对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="封面" prop="author">
          <el-upload :action="uploadImgUrl" :before-upload="beforeAvatarUpload"  :headers="headers"
            :on-success="handleAvatarSuccess" :show-file-list="false" class="avatar-uploader">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="书籍名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入书籍名称" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="form.desc" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="封面" prop="img">
          <el-input v-model="form.img" placeholder="请输入封面" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <treeselect v-model="form.category" :normalizer="normalizer" :options="tagOptions" :show-count="true"
            placeholder="请选择分类" style="display: inline-block; width: 200px;" />
        </el-form-item>
        <el-form-item label="书名" prop="bookName">
          <el-input v-model="form.bookName" placeholder="请输入书名" />
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入内容" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBook, getBook, delBook, addBook, updateBook } from "@/api/novel/book";
import { treeTag } from "@/api/novel/tag";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";

export default {
  name: "Book",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 标签树
      tagOptions: [],
      tagList: [],
      // 图书表格数据
      bookList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        author: null,
        status: null,
        type: null,
        title: null,
        desc: null,
        img: null,
        category: null,
        bookName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      imageUrl: '',
      // 图片上传地址
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
    };
  },
  created() {
    this.getList();
    this.getTagList()
  },
  methods: {
    /** 查询图书列表 */
    getList() {
      this.loading = true;
      listBook(this.queryParams).then(({ data }) => {
        this.bookList = data.records;
        this.total = data.total;
        this.loading = false;
      });
    },
    /** 查询标签分类列表 */
    getTagList() {
      this.loading = true;
      treeTag().then(({ data }) => {
        this.tagList = data;
        // this.total = data.total;
        this.loading = false;
        this.getTreeselect()
      });
    },
    /** 查询标签下拉树结构 */
    getTreeselect() {
      this.tagOptions = [];
      const tag = { id: -1, name: '主标签', subTags: [] };
      tag.subTags = this.tagList;
      this.tagOptions.push(tag);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        author: null,
        status: null,
        type: null,
        title: null,
        desc: null,
        img: null,
        category: null,
        bookName: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    //拼接图片URL
    getImgURL(name) {
      if(name.startsWith("/profile/")){
        console.log(name)
        return process.env.VUE_APP_BASE_API + name;
      }
      return process.env.VUE_APP_BASE_API + "/profile/novel/" + name;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加图书";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBook(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改图书";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBook(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBook(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除图书编号为"' + ids + '"的数据项？').then(function () {
        return delBook(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/book/export', {
        ...this.queryParams
      }, `book_${new Date().getTime()}.xlsx`)
    },
    /** 转换标签数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.subTags
      };
    },
    // 图片上传成功
    handleAvatarSuccess(res, file) {
      this.form.img = res.fileName;
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    // 图片上传前
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return  isLt2M;
    }
  }
};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 178px;
  display: block;
}
</style>
